// stores/energyUsers.js
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { getEnergyUsersApi } from '@/api/energy_users'
import { handleError } from '@/utils/handleError'
import { useCompanyStore } from '@/stores/company'

export const useEnergyUsersStore = defineStore('energyUsers', () => {
    // 状态
    const energyUserList = ref([])
    const loading = ref(false)
    const sortConfig = ref({
        prop: 'unknown_ratio',
        order: 'descending'
    })
    const searchTerm = ref('')

    // 计算属性
    const filteredEnergyUsers = computed(() => {
        let result = energyUserList.value

        // 排序
        if (sortConfig.value.prop && sortConfig.value.order) {
            const isAsc = sortConfig.value.order === 'ascending'
            result = [...result].sort((a, b) => {
                const valueA = Number(a[sortConfig.value.prop])
                const valueB = Number(b[sortConfig.value.prop])
                return isAsc ? valueA - valueB : valueB - valueA
            })
        }

        return result
    })

    // 方法
    const fetchEnergyUsers = async (params = {}) => {
        const companyStore = useCompanyStore()
        loading.value = true
        try {
            // 如果有搜索词，添加%进行模糊搜索
            const searchParams = { ...params }
            if (searchTerm.value) {
                searchParams.name = `%${searchTerm.value}%`
            }
            let res = await getEnergyUsersApi({
                company_id: companyStore.currentCompany.id,
                ...searchParams
            })
            energyUserList.value = res.data
        } catch (error) {
            handleError(error, '获取用能户列表失败')
        } finally {
            loading.value = false
        }
    }

    //获取名字
    const getEnergyUserName = (id) => {
        const energyUser = energyUserList.value.find(item => item.id === id)
        return energyUser ? energyUser.name : '暂无'
    }

    return {
        energyUserList,
        loading,
        sortConfig,
        searchTerm,
        filteredEnergyUsers,
        fetchEnergyUsers,
        getEnergyUserName
    }
})